function Org(){
	//this.table=this.InitTable();
	this.comboboxm=this.InitParent();
    this.tab=this.InitTab();
	this.form=this.InitEleUI();
	//this.tree=this.InitTree();
	this.grid=this.InitGrid();
	$("#tree-content").height($(window).height()-100);
	
}

Org.prototype.InitParent = function() {
	var width=($(window).width()-50)*0.6*0.8-90;
	var comboboxm=$("#parentid").ligerComboBox({
		valueField : 'orgid',
		textField : 'orgname',
		selectBoxWidth : width-2,
		selectBoxHeight:300,
		treeLeafOnly:false,
		valueFieldID:"hid",
		tree: {url : '../common/get_org_list?orgtype=0',
			checkbox: false, 
			nodeWidth:width-100,
			ajaxType: 'get', 
			idFieldName: 'orgid',
			textFieldName:"orgname",
			idField:"orgid",
        	parentIDField:"orgparentid"
		},
		onSelected : function(orgid, orgname) {// id为空值，name为选择的值
			$("#hidparentid").val(orgid);
			
		},
		width : width
	});
	return comboboxm;
}

Org.prototype.InitEleUI=function(){
	var form;
	layui.use('form', function(){
       form = layui.form; // 只有执行了这一步，部分表单元素才会自动修饰成功

	   form.render();
	});  
	return form;
}
Org.prototype.InitTab=function(){
	var element;
	layui.use('element', function(){
	   element = layui.element;
	});
	return element;
}

Org.prototype.OpTab=function(tabindex,obj){
	this.tab.tabChange('tabcontent', tabindex);
	if(obj){
		 document.formedit.orgname.value=obj.orgname;
		 document.formedit.remark.value=obj.remark;
		 document.formedit.orgid.value=obj.orgid;
		 document.formedit.orderindex.value=obj.orderindex;
//		 $("#parentid").val(obj.orgparentid);
//		 $("#parentid").attr("disabled","disabled");
		 this.comboboxm.selectValue(obj.orgparentid);
		 this.comboboxm.setDisabled();
		 this.form.render();
		 //this.form.render('select');
		 
	}
}

Org.prototype.InitTree=function(){
	
	
	$.ajax({
		type:"POST",
		url:"get_list",
		data:{rolename: $("#rolename").val()},
		beforeSend:function(XHR){
			//{"rowNum":1,"orgid":19,"orgparentid":0,"orgname":"行政组织机构","orgtype":0,"lft":1,"rgt":110,"level":0,"path":null,"createtime":"2018-05-02 17:52:37","remark":"行政组织机构","ischecked":null,
		},
		success:function(data){
			data=eval('('+data+')');
			
			if(data.code==0){
				var treedata=[];
				var data=data.data;
				var treedata=createTreeData(data,0);
				//console.log(JSON.stringify(dd));
				
				layui.tree({
				  elem: '#tree' //传入元素选择器
				  ,nodes: treedata
				  ,skin: 'huang'
				});
				
				
			}
		},
		complete:function(XHR){
			
		},
		error:function(){
			
		}
	});
	

}

Org.prototype.InitTable = function() {
	var table;
	var _this=this;
	layui.use('table', function() {
	    table = layui.table;
		table.render({
			elem : '#list'
			,height : $(window).height() - 100
			,url : 'get_list' // 数据接口
			,page : true // 开启分页
			,limit : 30
			,id: 'orglist'
			,method:"post"
			,cols : [ [ // 表头
			           {type:'numbers'}
			           ,{field : 'orgname',title : '机构名称',width : 250,align : 'left'}
			           , {field : 'orderindex',title : '排序',width : 120,align : 'center'}
			           //, {field : 'createtime',title : '时间',width : 170,align : 'center'}
			           , {field : 'remark',title : '描述',width : 200,align : 'center'}
			           , {title : '操作',width : 150,align : 'center',toolbar : '#operate'}
		            ] ]
		    ,request:{
				type:'post'
			}
		    ,page: false
		    ,even: true //开启隔行背景
		    //,size: 'sm' //小尺寸的表格
			,where:{rolename: $("#rolename").val()}
		    ,done: function(res, page, count){
		    	var dataarr=res.data;
		    	$("[data-field='orgname']").children().each(function(index){ 
		    		if(index==0){
		    			$(this).css({"text-align":"center"});
		    		}
		    		var thisdata=dataarr[index-1];
		    		if(thisdata){
		    			var text=$(this).text();
		                $(this).css({"text-indent":thisdata.level+"em"});
		    		}
               })  
		    }
		    
		});

		
		 //监听工具条
	    table.on('tool(list)', function(obj){
	      var data = obj.data;
	      if(obj.event === 'detail'){
	        layer.msg('ID：'+ data.id + ' 的查看操作');
	      } else if(obj.event === 'del'){
	    	  
	        top.mylayui.confirm('确定要删除吗？',{icon: 0}, function(index,dd){
	        	 top.mylayui.close(index);
	        	 vOrg.deleteentity(data.orgid);
	        });
	      } else if(obj.event === 'edit'){
	        //layer.alert('编辑行：<br>'+ JSON.stringify(data))
	    	  _this.OpTab(2,data);
	      }
	    });

	    
	});
	
	return table;
}

Org.prototype.searchtable=function(){
	this.table.reload('orglist', { 
		  page: {
	        curr: 1 //重新从第 1 页开始
	      },page: false
	    ,where: {  
	  	  rolename: $("#rolename").val()  
	    }  
	}); 
}


Org.prototype.deleteentity=function(orgid){
	 top.mylayui.confirm('确定要删除吗？',{icon: 0}, function(index){
    	 top.mylayui.close(index);
	
	$.ajax({
		type:"POST",
		url:"delete_org",
		data:{orgid:orgid},
		beforeSend:function(XHR){
			
		},
		success:function(data){
			data=eval('('+data+')');
			if(data.result>0){
				top.mylayui.msg(data.msg, {icon: 1});
				//vOrg.searchtable();
				document.location.reload();
			}
			else{
				top.mylayui.msg(data.msg, {icon: 0});
			}
		},
		complete:function(XHR){
			
		},
		error:function(){
			
		}
	});
	 })
}

Org.prototype.funeditentity=function(orgid,orgname,orgparentid,remark,orderindex){
	var data={orgid:orgid,orgname:orgname,orgparentid:orgparentid,remark:remark,orderindex:orderindex};
	vOrg.OpTab(2,data);
}

Org.prototype.InitGrid=function (){
	var _this = this;
    window.liger.remove("list");
    if (_this.grid == null) {
        _this.grid = $("#list").ligerGrid({
            columns: [
                      //{ display: '序号', width: 80, name: 'rowNum' },
                     { display: '机构名称', width:250, align:'left',name: 'orgname',id:"orgname"},
                     { display: '排序', width:130, align:'center',name: 'orderindex'},
                    
                     { display: '描述', width: 200, name: 'remark' },
                     {display: '操作', width: 100, name: 'userid', render: function (rowdata, rowindex, value) {
                    	var html=' <img class="btn-img" style="vertical-align:middle" src="'+ctxStatic+'/images/index/btn_edit.png" onclick="vOrg.funeditentity('+rowdata.orgid+',\''+rowdata.orgname+'\','+rowdata.orgparentid+',\''+rowdata.remark+'\','+rowdata.orderindex+')"  alt="编辑" title="编辑">';
                    	html+='<img class="btn-img" style="vertical-align:middle" src="'+ctxStatic+'/images/index/btn_delete.png" onclick="vOrg.deleteentity('+rowdata.orgid+')"  alt="删除" title="删除">';
                    	return html;
                     }}
            ],
            pageSize: 30,
            url: "get_list" + '?time=' + new Date().getTime(),
            delayLoad: false,            //初始化时是否加载,为true时,不加载,为false时,则加载
            sortName: null,
            dataAction: 'server',
            parms: {
                Method: "",
                rolename: $("#rolename").val()
            },
            sortOrder: null,
            sourceObj: _this.grid,
            root: 'items',                       //数据源字段名
            record: 'countRecord',                    //数据源记录数字段名
            pageParmName: 'CurrentPage',               //页索引参数名，(提交给服务器)
            pagesizeParmName: 'PageSize',        //页记录数参数名，(提交给服务器)
            data: {},
            width: "100%",
            height: '100%',
            heightDiff: 0,
            rowHeight:28,
            onSuccess: function (rowdata, rowindex) { if (rowdata.status > 0) { alert(rowdata.msg) } },
            alternatingRow: true,
            border: 0,
            usePager:false,
            tree:{
            	columnId:"orgname",
            	idField:"orgid",
            	parentIDField:"orgparentid"
            	
            },onAfterShowData:function () {
                $("#list").ligerGrid().collapseAll();
            }
        })
    }
}


var vOrg;
$(function () {
	vOrg = new Org();
})


function CloseDialog(result,msg){
	if(result>0){
		top.mylayui.msg('操作成功', {icon: 1});
		document.formedit.reset();
		//vOrg.searchtable();
		//vOrg.OpTab(1);
		document.location.reload();
	}
	else{
		if(msg){
			top.mylayui.msg(msg, {icon: 0});
		}else{
			top.mylayui.msg('操作失败', {icon: 0});
		}
	}
}


/*
 * 传入的数组有id和父节点pid字段，通过它们的关联构造成一棵或多棵树结构
 * @param nodes 集合
 * @param treeRootId 根节点的id
 */
function createTreeData(nodes, treeRootId) {
    var groups = {};
    var treeRootPid=0;
    // 按父节点将节点分组
    for (var i in nodes) {
        if (!groups[nodes[i].orgparentid]) {
            groups[nodes[i].orgparentid] = [];
        }
        groups[nodes[i].orgparentid].push(nodes[i]);
        if (treeRootPid && treeRootPid === nodes[i].orgid) { // 发现传入的根节点id作为节点id时，将根节点设置为该节点的父节点
            treeRootPid = nodes[i].orgparentid;
        }
    }

    var rootNodes = groups[treeRootPid];
    //rootNodes.name=rootNodes.orgname;
    //rootNodes.id=rootNodes.orgid;
    groups[treeRootPid] = null; // [SAFEGUARD]防止自为父节点或互为父节点（有环图结构）导致的死循环
    function traverseTreeNodeGroup(treeNodeGroup) {
        for (var i in treeNodeGroup) {
            var node = treeNodeGroup[i];
            node.name=node.orgname;
            node.id=node.orgid;
            node.spread=true;
            if (groups[node.orgid]) {
                node.children = groups[node.orgid];
                groups[node.orgid] = null; // [SAFEGUARD]防止自为父节点或互为父节点（有环图结构）导致的死循环
                traverseTreeNodeGroup(node.children);
            }
        }
    }
    traverseTreeNodeGroup(rootNodes);
    return rootNodes;
}